import React, { FC, useEffect, useState } from 'react'
import noDataUrl from '@/assets/images/noData.png'
import Header from '@/components/home/header'
import { useNavigate } from 'react-router-dom'
import { Button, Dialog, Form, Input, Space, Switch, Toast } from 'antd-mobile'
import { AddressParam, StuAdd } from '@/types/address/userAdd'
import region from './region'
import { useAppSelector, useAppDispatch } from '@/store'
import { addressSave, addressDelete } from '@/api/address'
import SelectRegion from './selectRegion'
import { selectIsEditor, selectEditorStdAdd } from '@/store/address'

const welfare: FC<{}> = () => {
  const [form] = Form.useForm<Partial<StuAdd & { regiontext: string }>>()

  const isEditor = useAppSelector(selectIsEditor)
  const stdAdd = useAppSelector(selectEditorStdAdd)

  const [formData, setFormData] = useState<Partial<StuAdd & { regiontext: string }>>(
    isEditor
      ? {
          ...stdAdd,
          regiontext: stdAdd!.province_name ? stdAdd!.city_name + '' + stdAdd!.county_name : '',
        }
      : {},
  )
  useEffect(() => {
    form.setFieldsValue(formData)
  }, [])
  /**回退拦截 */
  const browserBack = () => {
    Dialog.confirm({
      bodyStyle: {
        width: '28rem',
        height: '14.4rem',
        textAlign: 'center',
        paddingTop: '2rem',
      },
      content: (
        <span className=" block relative top-r1.0 text-r1.6 text-gray-333333 font-medium-family font-medium text-center ">
          编辑的信息还未保存，确定返回？
        </span>
      ),
      onConfirm: () => {
        navigate(-1)
      },
      onCancel: () => {
        window.history.pushState({}, 'title', window.location.href)
      },
      cancelText: (
        <span className=" inline-block relative -top-r1.0 shadow-bs2   left-1/2 transform -translate-x-1/2 text-r1.4 leading-r4.0 h-r4.0 w-r11.2 text-gray-333333 font-normal rounded-r2.0  bg-gray-999999 bg-opacity-10 inline-block text-center ">
          取消
        </span>
      ),
      confirmText: (
        <span className=" inline-block relative -top-r1.0 shadow-bs4   left-1/2 transform -translate-x-1/2 text-r1.4 leading-r4.0 h-r4.0 w-r11.2 text-white rounded-r2.0  bg-gradient-to-r from-orange-FF664F to-orange-FF3627 inline-block text-center ">
          确定
        </span>
      ),
    })
  }
  useEffect(() => {
    if (history.state && history.state.title !== 'title') {
      const state = {
        title: 'title',
        url: '',
      }
      window.history.pushState(state, 'title', window.location.href)
      window.addEventListener('popstate', browserBack)
    }

    return () => {
      window.removeEventListener('popstate', browserBack, false)
    }
  }, [])
  const navigate = useNavigate()

  //地址保存
  const [regionVisible, setRegionVisible] = useState<boolean>(false)
  const [regionData, setRegionData] = useState<
    Partial<
      Pick<AddressParam, 'provinceId' | 'cityId' | 'countyId'> & {
        province_name: string
        city_name: string
        county_name: string
      }
    >
  >({
    province_name: stdAdd!.province_name,
    city_name: stdAdd!.city_name,
    county_name: stdAdd!.county_name,
  })

  /**保存 */
  const save = async (data: Partial<StuAdd & { regiontext: string }>) => {
    delete data.regiontext

    const res = await addressSave({
      id: data.id,
      realName: data.name,
      address: data.detail,
      phone: data.phone,
      isDefault: data.is_default ? 1 : 0,
      ...regionData,
    })
    if (res.result.status === 1) {
      navigate('/payment')
      location.reload()
    }
  }
  /**
   * 删除
   */
  const deleteAddress = async () => {
    const res = await addressDelete({ id: stdAdd!.id, 'X-Businessline-Id': 30 })
    Toast.show({
      content: res.data,
    })
    if (res.status === 1) {
      navigate(-1)
    }
  }

  return (
    <div className="w-full h-full  bg-gray-F9F9F9 ">
      <Header
        cb={() => {
          navigate(-1)
        }}
        // comfirmMsg={'编辑的信息还未保存，确定返回？'}
        headerText={'添加收货地址'}
      ></Header>
      <div className=" text-r1.4  text-gray-333333">
        <Form layout="horizontal" mode="card" form={form}>
          <Form.Item
            className=" text-r1.4  text-gray-333333"
            label="收货人"
            name="name"
            rules={[
              { required: true, message: '姓名不能为空' },
              { type: 'string', max: 20 },
            ]}
          >
            <Input placeholder="姓名" defaultValue={formData.name} />
          </Form.Item>
          <Form.Item
            className=" text-r1.4  text-gray-333333"
            label="联系电话"
            name="phone"
            rules={[{ required: true }, { len: 11 }]}
          >
            <Input placeholder="请输入11位手机号" defaultValue={formData.phone} />
          </Form.Item>
          <Form.Item
            className=" text-r1.4  text-gray-333333"
            label="所在地区"
            rules={[{ required: true }]}
            name="regiontext"
          >
            <div
              className="w-auto h-auto"
              onClick={() => {
                setRegionVisible(true)
              }}
            >
              <Input
                placeholder="选择所在地区"
                style={{ width: '21.0rem' }}
                className="overflow-ellipsis w-r10.0"
                readOnly
                value={
                  regionData.province_name
                    ? regionData.province_name +
                      '' +
                      regionData.city_name +
                      '' +
                      regionData.county_name
                    : ''
                }
              />
              <span className=" absolute z-10 right-r1.3 top-r1.5 bg-white">
                <i className="w-r2.0 h-r2.0 iconfont icon-icon_arrow_right"></i>
              </span>
            </div>
          </Form.Item>
          <Form.Item
            className=" text-r1.4  text-gray-333333"
            label="详细地址"
            name="detail"
            rules={[{ required: true }, { type: 'string', max: 100 }]}
          >
            <Input placeholder="街道门牌信息" defaultValue={formData.detail} />
          </Form.Item>
          <Form.Header />
          <div className=" w-full h-r0.5"></div>
          <Form.Item
            className=" text-r1.4  text-gray-333333"
            name="is_default"
            label={<span className=" w-r16.0 inline-block">设为默认地址</span>}
            childElementPosition="right"
          >
            <Switch defaultChecked={!!formData.is_default} />
          </Form.Item>
        </Form>
        <Form layout="horizontal" mode="card"></Form>
        {isEditor ? (
          <div className=" text-center">
            {' '}
            <span
              className="text-red-FF4A4A"
              onClick={async () => {
                deleteAddress()
              }}
            >
              删除地址
            </span>
          </div>
        ) : null}

        <div className=" p-r2.0">
          <span className=" text-r1.3 font-normal text-gray-666666 inline-block">温馨提示：</span>
          <span className=" text-r1.3 font-normal mt-r0.6 mb-r5.7 text-gray-666666 inline-block">
            我们需要收集您的收货人姓名、所在地区、详细地址、手机号码信息。您的[收货人姓名、所在地区、详细地址、手机号码信息]属于敏感个人信息。我们将严格遵守法律法规，采取相应的安全措施和控制制度，保护您的个人信息。但互联网并非绝对安全，请您知悉并理解:您向我们做出的，上述授权可能产生各种不利后果，包括但不限于第三方通过非法手段或方式恶意获取或使用您的信息，可能会给您造成人身或财产的损害，或是造成您预逾期利益减少或损失扩大，或是其他不良或不利影响等。
          </span>
        </div>
        <div className="w-full fixed bottom-r2.2 ">
          <span
            onClick={() => {
              form.validateFields().then((res) => {
                save(res)
              })
            }}
            className=" relative left-1/2 transform -translate-x-1/2 text-r1.4 h-r4.0 w-r21.9  text-white leading-r4.0 rounded-r2.0 bg-red-E02727 inline-block text-center "
          >
            保存并使用
          </span>
        </div>
      </div>
      {regionVisible ? (
        <SelectRegion
          setRegionVisible={setRegionVisible}
          setRegionData={setRegionData}
        ></SelectRegion>
      ) : null}
    </div>
  )
}

export default welfare
